package cn.edu.scau.cmi.ema.controller.rest;

import org.springframework.stereotype.Controller;

import java.util.List;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import java.io.IOException;

import com.google.gson.Gson;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;


import cn.edu.scau.cmi.ema.domain.base.CmiPagination;
import cn.edu.scau.cmi.ema.service.base.CmiPsonService;
import cn.edu.scau.cmi.ema.controller.base.CmiEmaController;
import cn.edu.scau.cmi.ema.dao.*;
import cn.edu.scau.cmi.ema.domain.*;
import cn.edu.scau.cmi.ema.service.*;

import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.WebDataBinder;

@Controller("DetectRestController")
public class DetectRestController extends CmiEmaController {

	/**
	 * Create a new Detect entity
	 * 
	 */
	@RequestMapping(value = "/newDetect", method = RequestMethod.POST)
	@ResponseBody
	public Object newDetect(@RequestBody Detect detect) {
		detectService.saveDetect(detect);
		return JSONObject.parse(cmiPsonService.toJsonString(detectDAO.findDetectByPrimaryKey(detect.getId()), 2));
	}

	@RequestMapping(value = "/restNewDetect", method = RequestMethod.POST)
	@ResponseBody
	public Object restNewDetect(@RequestBody String detectJson) {
		Detect detect = new Gson().fromJson(detectJson, Detect.class);
		appendReferences(detect);
		detectService.saveDetect(detect);
		return JSONObject.parse(cmiPsonService.toJsonString(detectDAO.findDetectByPrimaryKey(detect.getId()), 2));
	}

	@RequestMapping(value = "/saveDetect", method = RequestMethod.PUT)
	@ResponseBody
	public Detect saveDetect(@RequestBody Detect detect) {
		detectService.saveDetect(detect);
		return detectDAO.findDetectByPrimaryKey(detect.getId());
	}

	@RequestMapping(value = "/restSaveDetect", method = RequestMethod.PUT)
	@ResponseBody
	public Object restSaveDetect(@RequestBody String detectJson) {
		Detect detect = new Gson().fromJson(detectJson, Detect.class);
		appendReferences(detect);
		CmiPsonService cmiPsonService = new CmiPsonService();
		detectService.saveDetect(detect);
		return JSONObject.parse(cmiPsonService.toJsonString(detectDAO.findDetectByPrimaryKey(detect.getId()), 1));
	}

	@RequestMapping(value = "/restDeleteDetect/{detectId}", method = RequestMethod.DELETE)
	@ResponseBody
	public void restDeleteDetect(@PathVariable Integer detectId) {
		Detect detect = detectDAO.findDetectByPrimaryKey(detectId);
		detectService.deleteDetect(detect);
	}

	@RequestMapping(value = "/restConfirmDeleteDetects")
	@ResponseBody
	public Object restConfirmDeleteDetects(@RequestBody Set<Integer> deleteDetectsIds) {
		Set<Detect> deleteDetects = detectDAO.findDetectsByIds(deleteDetectsIds);
		Set<Detect> referencedDetects = detectService.loadReferenceDetects(deleteDetects);
		deleteDetects.removeAll(referencedDetects);
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("referencedEntitys", referencedDetects);
		jsonObject.put("deleteEntitys", deleteDetects);
		return JSONObject.parse(jsonObject.toJSONString());
	}

	@RequestMapping("/restDeleteDetects")
	@ResponseBody
	public Object restDeleteDetects(@RequestBody Set<Detect> deleteDetects) {
		Iterator<Detect> iterator = deleteDetects.iterator();
		while (iterator.hasNext()) {
			Detect currentDetect = iterator.next();
			detectService.deleteDetect(currentDetect);
		}
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("url", "listDetects");
		return JSONObject.parse(jsonObject.toJSONString());
	}
	// loadself

	@RequestMapping(value = "/restLoadDetect/{detectId}", method = RequestMethod.POST)
	@ResponseBody
	public Object restLoadDetect(@PathVariable Integer detectId, @RequestBody CmiPagination cmiPagination) {
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(cmiPsonService.toPsonString(detectDAO.findDetectByPrimaryKey(detectId), 2, cmiPagination));
	}

	@RequestMapping(value = "/restLoadDetectDetectdepartment/{detectId}/detectdepartment", method = RequestMethod.POST)
	@ResponseBody
	public Object restLoadDetectDetectdepartment(@PathVariable Integer detectId,
			@RequestBody CmiPagination cmiPagination) {
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(cmiPsonService.toPsonString(detectDAO.findDetectByPrimaryKey(detectId).getDetectdepartment(),
				2, cmiPagination));
	}

	@RequestMapping(value = "/restLoadDetectFoodbatch/{detectId}/foodbatch", method = RequestMethod.POST)
	@ResponseBody
	public Object restLoadDetectFoodbatch(@PathVariable Integer detectId, @RequestBody CmiPagination cmiPagination) {
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(
				cmiPsonService.toPsonString(detectDAO.findDetectByPrimaryKey(detectId).getFoodbatch(), 2, cmiPagination));
	}

	@RequestMapping(value = "/restLoadDetectUser/{detectId}/user", method = RequestMethod.POST)
	@ResponseBody
	public Object restLoadDetectUser(@PathVariable Integer detectId, @RequestBody CmiPagination cmiPagination) {
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(
				cmiPsonService.toPsonString(detectDAO.findDetectByPrimaryKey(detectId).getDetector(), 2, cmiPagination));
	}

	@RequestMapping(value = "/restLoadDetectSubject/{detectId}/subject", method = RequestMethod.POST)
	@ResponseBody
	public Object restLoadDetectSubject(@PathVariable Integer detectId, @RequestBody CmiPagination cmiPagination) {
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(
				cmiPsonService.toPsonString(detectDAO.findDetectByPrimaryKey(detectId).getSubject(), 2, cmiPagination));
	}
	// loadReferenceds
	// TODO loadReferencedsPson，这个方法有一些问题，待修复

	@RequestMapping(value = "/restLoadDetectDetectdetails/{detectId}/detectdetails/{relateddetectdetailId}", method = RequestMethod.POST)
	@ResponseBody
	public Object restLoadDetectDetectdetails(@PathVariable Integer detectId,
			@PathVariable Integer relateddetectdetailId, @RequestBody CmiPagination cmiPagination) {
		Detectdetail detectdetail = detectdetailDAO.findDetectdetailByPrimaryKey(relateddetectdetailId, -1, -1);
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(cmiPsonService.toPsonString(detectdetail, 2, cmiPagination));
	}

	@RequestMapping(value = "/restLoadDetectDetectfeatures/{detectId}/detectfeatures/{relateddetectfeatureId}", method = RequestMethod.POST)
	@ResponseBody
	public Object restLoadDetectDetectfeatures(@PathVariable Integer detectId,
			@PathVariable Integer relateddetectfeatureId, @RequestBody CmiPagination cmiPagination) {
		Detectfeature detectfeature = detectfeatureDAO.findDetectfeatureByPrimaryKey(relateddetectfeatureId, -1, -1);
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(cmiPsonService.toPsonString(detectfeature, 2, cmiPagination));
	}

	public void appendReferences(Detect detect) {

		Detectdepartment detectdepartment = detect.getDetectdepartment();
		if (detectdepartment != null)
			detect.setDetectdepartment(
					detectdepartmentService.findDetectdepartmentByPrimaryKey(detectdepartment.getId()));

		Foodbatch foodbatch = detect.getFoodbatch();
		if (foodbatch != null)
			detect.setFoodbatch(foodbatchService.findFoodbatchByPrimaryKey(foodbatch.getId()));

		User detector = detect.getDetector();
		if (detector != null)
			detect.setDetector(userService.findUserByPrimaryKey(detector.getId()));

		Subject subject = detect.getSubject();
		if (subject != null)
			detect.setSubject(subjectService.findSubjectByPrimaryKey(subject.getId()));

		// 引用表不是纯联系表，引用数量大于或者等于2
		Set<Detectdetail> detectdetailsForDetect = new HashSet<>();
		for (Detectdetail detectdetail_Detect : detect.getDetectdetailsForDetect()) {
			detectdetailsForDetect.add(detectdetailService.findDetectdetailByPrimaryKey(detectdetail_Detect.getId()));
		}
		detect.setDetectdetailsForDetect(detectdetailsForDetect);

		// 引用表不是纯联系表，引用数量大于或者等于2
		Set<Detectfeature> detectfeaturesForDetect = new HashSet<>();
		for (Detectfeature detectfeature_Detect : detect.getDetectfeaturesForDetect()) {
			detectfeaturesForDetect
					.add(detectfeatureService.findDetectfeatureByPrimaryKey(detectfeature_Detect.getId()));
		}
		detect.setDetectfeaturesForDetect(detectfeaturesForDetect);
	}

	@RequestMapping(value = "/restGetDetectDetectdepartment/{detectId}/detectdepartment", method = RequestMethod.POST)
	@ResponseBody
	public Object restGetDetectDetectdepartment(@PathVariable Integer detectId,
			@RequestBody CmiPagination cmiPagination) {
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(cmiPsonService.toPsonString(detectDAO.findDetectByPrimaryKey(detectId).getDetectdepartment(),
				2, cmiPagination));
	}

	@RequestMapping(value = "/restGetDetectFoodbatch/{detectId}/foodbatch", method = RequestMethod.POST)
	@ResponseBody
	public Object restGetDetectFoodbatch(@PathVariable Integer detectId, @RequestBody CmiPagination cmiPagination) {
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(
				cmiPsonService.toPsonString(detectDAO.findDetectByPrimaryKey(detectId).getFoodbatch(), 2, cmiPagination));
	}

	@RequestMapping(value = "/restGetDetectUser/{detectId}/user", method = RequestMethod.POST)
	@ResponseBody
	public Object restGetDetectUser(@PathVariable Integer detectId, @RequestBody CmiPagination cmiPagination) {
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(
				cmiPsonService.toPsonString(detectDAO.findDetectByPrimaryKey(detectId).getDetector(), 2, cmiPagination));
	}

	@RequestMapping(value = "/restGetDetectSubject/{detectId}/subject", method = RequestMethod.POST)
	@ResponseBody
	public Object restGetDetectSubject(@PathVariable Integer detectId, @RequestBody CmiPagination cmiPagination) {
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(
				cmiPsonService.toPsonString(detectDAO.findDetectByPrimaryKey(detectId).getSubject(), 2, cmiPagination));
	}

	@RequestMapping(value = "/restGetDetectDetectdetails/{detectId}/detectdetails", method = RequestMethod.POST)
	@ResponseBody
	public Object restGetDetectDetectdetails(@PathVariable Integer detectId, @RequestBody CmiPagination cmiPagination) {
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(cmiPsonService
				.toPsonString(detectDAO.findDetectByPrimaryKey(detectId).getDetectdetailsForDetect(), 2, cmiPagination));
	}

	@RequestMapping(value = "/restGetDetectDetectfeatures/{detectId}/detectfeatures", method = RequestMethod.POST)
	@ResponseBody
	public Object restGetDetectDetectfeatures(@PathVariable Integer detectId,
			@RequestBody CmiPagination cmiPagination) {
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(cmiPsonService
				.toPsonString(detectDAO.findDetectByPrimaryKey(detectId).getDetectfeaturesForDetect(), 2, cmiPagination));
	}

	@RequestMapping(value = "/restListDetects", method = RequestMethod.GET)
	@ResponseBody
	public Object restListDetects() {
		return JSONObject.parse(cmiPsonService.toJsonString(detectService.loadDetects(), 2));
	}

	@RequestMapping(value = "/restListDetectsPost", method = RequestMethod.POST)
	@ResponseBody
	public Object restListDetectsPost(@RequestBody CmiPagination cmiPagination) {

		CmiPsonService cmiPsonService = new CmiPsonService();
		cmiPagination = detectPaginationService.updateAppPagination(cmiPagination);
		int startResult = (cmiPagination.getCurrentPagination() - 1) * cmiPagination.getPaginationSize();

		Set<Detect> detects = detectDAO.findAllDetects(startResult, cmiPagination.getPaginationSize());
		String detectString = cmiPsonService.toPsonString(detects, 2, cmiPagination);

		return JSONObject.parse(detectString);
	}

	@RequestMapping("/detectSelectBox")
	@ResponseBody
	public JSONObject detectSelectBox(@RequestParam(required = false) String searchTable,
			@RequestParam(required = false) Set<Integer> searchValue, // 杨宏宇2019-9-10：searchValue是在selectpage.js的616行定义，如果要修改searchValue的名称，1.可以修改在selectpage.js修改；2.可以
																		// @RequestParam(value="searchValue", required =
																		// false) Set<Integer> someName
			@RequestParam(required = false, defaultValue = "10") int paginationSize,
			@RequestParam(required = false, defaultValue = "1") int pageNumber,
			@RequestParam(value = "qWord[]", required = false) String queryword,
			@RequestParam(required = false) String selectItem) throws IOException {
		Set entitySet = null;
		Integer count = 0;

		// 初始化原始值

		if (searchValue != null) {
			switch (searchTable) {
			// 外键
			case "Detectdepartment":
				entitySet = detectdepartmentService.loadDetectdepartmentsByIdSet(searchValue);
				break;
			case "Foodbatch":
				entitySet = foodbatchService.loadFoodbatchsByIdSet(searchValue);
				break;
			case "User":
				entitySet = userService.loadUsersByIdSet(searchValue);
				break;
			case "Subject":
				entitySet = subjectService.loadSubjectsByIdSet(searchValue);
				break;

			// 被引用键
			case "Detectdetail":
				entitySet = detectdetailService.loadDetectdetailsByIdSet(searchValue);
				break;
			case "Detectfeature":
				entitySet = detectfeatureService.loadDetectfeaturesByIdSet(searchValue);
				break;
			}
			// 没有测试，深度需要多少？？？
			String jsonData = cmiPsonService.toJsonString(entitySet, 1);
			JSONArray jsonArray = new JSONArray();
			jsonArray = (JSONArray) JSON.parse((String) jsonData);

			JSONObject jsonObject = new JSONObject();
			jsonObject.put("list", jsonArray);
			jsonObject.put("totalRow", entitySet.size());
			return jsonObject;
		}

		// 不根据关键字进行搜索
		if (queryword == null || queryword.trim() == "") {
			switch (selectItem) {
			// 外键
			case "Detectdepartment":
				entitySet = detectdepartmentDAO.findAllDetectdepartments((pageNumber - 1) * paginationSize,
						paginationSize);
				count = detectdepartmentService.countDetectdepartments();
				break;
			case "Foodbatch":
				entitySet = foodbatchDAO.findAllFoodbatchs((pageNumber - 1) * paginationSize, paginationSize);
				count = foodbatchService.countFoodbatchs();
				break;
			case "User":
				entitySet = userDAO.findAllUsers((pageNumber - 1) * paginationSize, paginationSize);
				count = userService.countUsers();
				break;
			case "Subject":
				entitySet = subjectDAO.findAllSubjects((pageNumber - 1) * paginationSize, paginationSize);
				count = subjectService.countSubjects();
				break;

			// 被引用键
			case "Detectdetail":
				entitySet = detectdetailDAO.findAllDetectdetails((pageNumber - 1) * paginationSize, paginationSize);
				count = detectdetailService.countDetectdetails();
				break;
			case "Detectfeature":
				entitySet = detectfeatureDAO.findAllDetectfeatures((pageNumber - 1) * paginationSize, paginationSize);
				count = detectfeatureService.countDetectfeatures();
				break;
			}
		} else {
			switch (selectItem) {
			// 外键
			case "Detectdepartment":
				entitySet = detectdepartmentDAO.findDetectdepartmentByNameContaining(queryword,
						(pageNumber - 1) * paginationSize, paginationSize);
				count = detectdepartmentService.countDetectdepartmentsByName(queryword);
				break;
			case "Foodbatch":
				entitySet = foodbatchDAO.findFoodbatchByNameContaining(queryword, (pageNumber - 1) * paginationSize,
						paginationSize);
				count = foodbatchService.countFoodbatchsByName(queryword);
				break;
			case "User":
				entitySet = userDAO.findUserByNameContaining(queryword, (pageNumber - 1) * paginationSize,
						paginationSize);
				count = userService.countUsersByName(queryword);
				break;
			case "Subject":
				entitySet = subjectDAO.findSubjectByNameContaining(queryword, (pageNumber - 1) * paginationSize,
						paginationSize);
				count = subjectService.countSubjectsByName(queryword);
				break;

			// 被引用键
			case "Detectdetail":
				entitySet = detectdetailDAO.findDetectdetailByNameContaining(queryword,
						(pageNumber - 1) * paginationSize, paginationSize);
				count = detectdetailService.countDetectdetailsByName(queryword);
				break;
			case "Detectfeature":
				entitySet = detectfeatureDAO.findDetectfeatureByNameContaining(queryword,
						(pageNumber - 1) * paginationSize, paginationSize);
				count = detectfeatureService.countDetectfeaturesByName(queryword);
				break;
			}
		}
		/**
		 * 将Json数据转换成jsonArray形式，需要通过pson方式进行转换，然后再转换成JsonArray。因为存在懒加载
		 * 没有直接使用CmiPsonService中的fromJson方法是因为，fromJson方法会将int类型的直接转换成double类型的数据，这个问题还没有解决
		 */
		// 没有测试，深度需要多少？？？
		String jsonData = cmiPsonService.toJsonString(entitySet, 1);
		JSONArray jsonArray = new JSONArray();
		jsonArray = (JSONArray) JSON.parse((String) jsonData);

		JSONObject jsonObject = new JSONObject();
		jsonObject.put("list", jsonArray);
		jsonObject.put("paginationSize", paginationSize);
		jsonObject.put("pageNumber", pageNumber);
		jsonObject.put("totalRow", count);
		jsonObject.put("totalPaginations",
				count % paginationSize == 0 ? count / paginationSize : count / paginationSize + 1);
		return jsonObject;
	}
}
